$(document).ready(function() {
    //坐标轴列表
    window.axisList = ""
    //是否绘制网格虚线的标志
    window.isShowGrid = true;
    //曲线是否拖动, 默认为false
    window.isDraggle = false;
    //曲线放大是否开启,默认为false
    window.isZoomIn = false;
    //曲线是否放大过
    window.isZoomedIn = false;
    //获取页面上的曲线区域
    window.curveArea = $('#curveArea');
    //获取页面上的svg
    window.svg = $('#svgCurveLines');
    //获取页面上的三个canvas(通过jquery和js两种方式获取)
    window.canvas = $("#myCanvas");
    window.canvas2 = $("#myCanvas2");
    window.gridCanvas = $("#gridCanvas");

    window.ctx = canvas[0].getContext("2d");
    window.ctx2 = canvas2[0].getContext("2d");
    window.ctx_gridCanvas = gridCanvas[0].getContext("2d");

    window.canves_js = document.getElementById("myCanvas");
    window.canves2_js = document.getElementById("myCanvas2");
    window.canves_gridCanvas_js = document.getElementById("gridCanvas");

    window.context = canves_js.getContext("2d");
    window.context2 = canves2_js.getContext("2d");
    window.context_gridCanvas = canves_gridCanvas_js.getContext("2d");


    //通过js设置svg和canves的宽和高(css设置会导致变形)
    let pageWidth = $(window).width();
    let pageHeight = $(window).height();
    console.log("浏览器的高度为" + pageHeight);
    $(".middle_curve").height(pageHeight);
    //工具箱和坐标轴列表占用的高度
    let otherHeight = $(".middle_tools").height() + $(".middle_axisList").height();
    pageHeight = pageHeight - otherHeight;

    canves_js.width = pageWidth;
    canves_js.height = pageHeight;
    canves2_js.width = pageWidth;
    canves2_js.height = pageHeight;
    canves_gridCanvas_js.width = pageWidth;
    canves_gridCanvas_js.height = pageHeight;

    svg.width(pageWidth);
    svg.height(pageHeight);

    //x0和y0为坐标原点的绝对位置
    window.x0 = 30; //坐标轴起始点X坐标
    window.y0 = pageHeight * 0.9; //坐标轴起始点Y坐标
    window.xMin = 0; //X最小像素
    window.xMax = pageWidth * 0.9; //X最大像素
    window.yMin = 0; //Y最小像素
    window.yMax = pageHeight * 0.8; //Y最大像素(顶部预留出一部分像素)
    window.yRemainder = pageHeight * 0.1; //Y轴顶部预留出的像素

    window.canvasWrapY = $('#svgCurveLines').offset().top; //Wrap左上角Y坐标
    window.canvasWrapX = $('#svgCurveLines').offset().left; //Wrap左上角X坐标
    //等待左侧曲线数据加载完毕
    // let i = 0;
    // while (i < 10) {
    // 	console.log("曲线加载中,请稍后");
    // 	if (sessionStorage.getItem("sensorValueStatus") == "finish") {
    // 		console.log("曲线加载完毕");
    //
    // 		//1.根据实验室编码查询所有的在测台位铭牌信息(测试元数据)-----middle
    // 		getAllTestProdInfoValueNow(top.labcode);
    //
    // 		//2.设置坐标轴列表-----middle
    // 		setAxisList();
    //
    // 		//3.绘制XY坐标系-----middle
    // 		paintSvgXY(x0, y0, xMax, yMax);
    //
    // 		//绘制网格虚线
    // 		//paintDashed(x0, y0, xMax, yMax);
    // 		drawGrid(80, 80);
    // 		//4.绘制传感器对应的曲线-----middle
    // 		let sensorArray = parent.getAllSelectSeneor();
    // 		for (j = 0, len = sensorArray.length; j < len; j++) {
    // 			paintSvgCurveLine(sensorArray[j]);
    // 		}
    //
    // 		break;
    // 	} else {
    // 		i++;
    // 		//让程序休眠2秒钟
    // 		//sleep(2000);//此方法会阻塞程序运行
    //        setTimeout(function(){
    //            console.log("曲线加载中,请稍后");
    //        },2000);
    // 	}
    //
    // }

    setTimeout(function() {
        if (sessionStorage.getItem("sensorValueStatus") != "finish") {
            console.log("曲线加载失败,请刷新重试");
            return;
        }
        //1.根据实验室编码查询所有的在测台位铭牌信息(测试元数据)-----middle
        getAllTestProdInfoValueNow(top.labcode);

        //2.设置坐标轴列表-----middle
        setAxisList();

        //3.绘制XY坐标系-----middle
        paintSvgXY(x0, y0, xMax, yMax);

        //绘制网格虚线
        //paintDashed(x0, y0, xMax, yMax);
        drawGrid(80, 80);
        //4.绘制传感器对应的曲线-----middle
        let sensorArray = parent.getAllSelectSeneor();
        for (j = 0, len = sensorArray.length; j < len; j++) {
            paintSvgCurveLine(sensorArray[j]);
        }
        parent.layer.close(parent.layerCurse); //手动关闭父页面中的layer
    }, 3000);


    var menu = new BootstrapMenu('#curveArea', {
        actionsGroups : [
            [ 'enlarge', 'curveMoveClose', 'curveMoveOpen', 'dataCompare', 'gridHidden', 'gridShow' ],
            [ 'shunRemark', 'clrarLabel' ],
            [ 'newCurve' ]
        ],
        actions : {
            zoomInOpen : {
                name : '曲线放大',
                iconClass : 'fa-unlock',
                onClick : function() {
                    zoomIn();
                },
                isShown : function() {
                    return isZoomIn;
                }
            },
            zoomInClose : {
                name : '曲线放大',
                iconClass : 'fa-lock',
                onClick : function() {
                    zoomIn();
                },
                isShown : function() {
                    return !isZoomIn;
                }
            },
            zoomInRestore : {
                name : '放大还原',
                iconClass : 'fa-refresh',
                onClick : function() {
                    zoomInRestore();
                },
                isShown : function() {
                    //1.曲线放大开着 放大了开着，那么开着
                    if (isZoomedIn && isZoomIn) {
                        return true;
                    }

                    //2.曲线放大关了 或 放大了关了，那么关了
                    if (!isZoomIn || !isZoomedIn) {
                        return false;
                    }
                }
            },
            lastZoomIn : {
                name : '放大返回',
                iconClass : 'fa-reply',
                onClick : function() {
                    lastZoomIn();
                },
                isShown : function() {
                    //1.曲线放大开着 放大了开着，那么开着
                    if (isZoomedIn && isZoomIn) {
                        return true;
                    }

                    //2.曲线放大关了 或 放大了关了，那么关了
                    if (!isZoomIn || !isZoomedIn) {
                        return false;
                    }
                }
            },
            curveMoveClose : {
                name : '曲线移动',
                iconClass : 'fa-lock',
                onClick : function() {
                    curveMove();
                },
                isShown : function() {
                    return !isDraggle;
                }
            },
            curveMoveOpen : {
                name : '曲线移动',
                iconClass : 'fa-unlock',
                onClick : function() {
                    curveMove();
                },
                isShown : function() {
                    return isDraggle;
                }
            },
            dataCompare : {
                name : '数据对比',
                iconClass : 'fa-exchange',
                onClick : function() {
                    dataCompare();
                }
            },
            shunRemark : {
                name : '瞬时数据标注',
                iconClass : 'fa-deafness',
                onClick : function() {
                    shunRemark();
                }
            },
            gridHidden : {
                name : '隐藏网格',
                iconClass : 'fa-square-o',
                onClick : function() {
                    showGrid();
                },
                isShown : function() {
                    return !isShowGrid;
                }
            },
            gridShow : {
                name : '显示网格',
                iconClass : 'fa-table',
                onClick : function() {
                    showGrid();
                },
                isShown : function() {
                    return isShowGrid;
                }
            },
            clrarLabel : {
                name : '清除所有标注',
                iconClass : 'fa-scissors',
                onClick : function() {
                    clearFlag();
                }
            },
            newCurve : {
                name : '显示最新曲线',
                iconClass : 'fa-trash-o',
                onClick : function() {
                    showNewCurve();
                }
            }
        }
    });

//循环执行设置详细数据动态数值
//window.setInterval(setDetailDataValue, 500);
});

//*******************************中间方法****************************
//1.根据实验室编码查询所有的在测台位铭牌信息(测试元数据)-----middle
function getAllTestProdInfoValueNow(labcode) {
    let topBasePath = getTopBasePath(top.basePath);
    $.ajax({
        type : "get",
        async : false, //设置为同步请求,防止接收不到数据
        url : "http://localhost/consumer/CurveInfoAPI/getAllTestProdInfoValueNow",
        data : {
            labcode : labcode,
        },
        success : function(msg) {
            if (msg.length > 0) {
                for (var i = 0; i < msg.length; i++) {
                    //设置台位的primarykey
                    $.cookie("testunitno" + msg[i].testunitno, msg[i].primarykey);
                }
            }
        },
        error : function(e) {
            alert("网页发生错误：", e, "error");
        }
    });
}

//2.设置坐标轴列表-----middle
function setAxisList() {
    //yyi 修改定义
    let nowprimarykey = "2019-04-28 16:12:001"
    //let topBasePath = getTopBasePath(top.basePath);
    //let nowprimarykey = $.cookie('nowprimarykey');
    $.ajax({
        type : "get",
        async : false, //设置为同步请求,防止接收不到数据
        url : "http://localhost/consumer/CurveInfoAPI/getCoordonate",
        data : {
            primaryKey : nowprimarykey
        },
        success : function(msg) {
            //坐标轴列表赋值
            axisList = msg;
            $("#axisList").nextAll().remove();
            var str = "";
            for (var i = 0; i < msg.length; i++) {
                //坐标系单位(调用的是最顶层)
                let sensorunit = "" + top.trim(msg[i].sensorunit);
                //坐标系是否被选中
                let visible = msg[i].visible;
                if (visible == "1") {
                    str += "<label class='btn btn-default btn-xs middle_label'>" +
                        "<input type='checkbox' checked='checked' onclick='paintMultyYaxis(x0, y0, yMax)'>" +
                        "<label class='axisName' onclick='showYWindow(&quot;" + sensorunit + "&quot;)'>" + msg[i].name + "</label>" +
                        "</label>";
                } else {
                    str += "<label class='btn btn-default btn-xs middle_label'>" +
                        "<input type='checkbox' onclick='paintMultyYaxis(x0, y0, yMax)'>" +
                        "<label class='axisName' onclick='showYWindow(&quot;" + sensorunit + "&quot;)'>" + msg[i].name + "</label>" +
                        "</label>";
                }
                //将坐标系信息存入session Storage中
                //注意:sessionStorage只能存储字符串类型数据，无法直接存储数组类型和JSON对象
                //需要将JSON对象通过JSON.stringify()方法转换成字符串，再存储到sessionstorage中
                sessionStorage.setItem("coordinateno" + msg[i].coordinateno, JSON.stringify(msg[i]));
            }
            $("#axisList").html(str);


        },
        error : function(e) {
            alert("网页发生错误：", e, "error");
        }
    });
}

//2.纵坐标上下限设置窗口
function showYWindow(sensorunit) {
    $('#winY').window('open');
    //设置纵坐标上下限单位
    $('#topYlimit').attr('placeholder', "单位为:" + sensorunit);
    $('#bottomYlimit').attr('placeholder', "单位为:" + sensorunit);
}

//2.改变纵坐标(Y轴)上下限
function changeYaxisValue() {
    var topYlimit = $("#topYlimit").val();
    var bottomYlimit = $("#bottomYlimit").val();
    if (!isNumber(topYlimit) || !isNumber(bottomYlimit)) {
        sweetAlert("警告", "上下限只能为数字", "warning");
        return;
    }
    if (parseInt(topYlimit) <= parseInt(bottomYlimit)) {
        sweetAlert("警告", "上限不能小于下限！", "warning");
        return;
    }
    //更新坐标轴的上下限


    //重新获取坐标轴列表
    setAxisList();

    //重新绘制y轴
    paintMultyYaxis(x0, y0, yMax);

    //重新绘制曲线
    paintSvgCurveLine(sensorno);

    //关闭窗口
    $('#winY').window('close');
}


//3.绘制XY坐标系-----middle
function paintSvgXY(xo, yo, xMax, yMax) {
    //方案1:从全局变量中获取总测试时间
    // if (parent.timeLong != "") {
    //     //3.1绘制X轴
    //     paintXaxis(xo, yo, xMax);
    // }
    //方案2:从sessionStorage中获取总测试时间
    if (sessionStorage.getItem("timeLong") != "") {
        //3.1绘制X轴
        paintXaxis(xo, yo, xMax);
    }

    //3.2绘制多个Y轴
    paintMultyYaxis(xo, yo, yMax);

}

//3.1.绘制X轴-----middle
function paintXaxis(xo, yo, xMax) {
    //清空svg画布中的X轴线条和刻度
    $(".XAxis").remove()
    $(".xAxisScale").remove()

    //X轴颜色
    let xAxisColor = "#fff";
    let svg = $('#svgCurveLines');
    //	var axisXPoints = xo + "," + yo + " " + xMax + "," + yo;
    var axisXPoints = -9000 + "," + yo + " 9000," + yo;
    var axisX = '<polyline points="' + axisXPoints + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:0.6" />';
    //绘制X箭头
    //	var arrowsWidth = 5;
    //	var arrowsXPoints = (xMax - arrowsWidth) + "," + (yo - arrowsWidth) + " " + xMax + "," + yo + " " + (xMax - arrowsWidth) + "," + (yo + arrowsWidth);
    //	var arrowsX = '<polyline points="' + arrowsXPoints + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';

    //	svg.html(svg.html() + axisX + arrowsX); //绘制
    svg.html(svg.html() + axisX); //绘制
    //绘制X轴刻度
    //小刻度分成20段,大刻度分成10段
    var minlen = 20;
    var maxlen = 10;
    //X轴 最大像素与最大刻度的比例
    //方案1:从全局变量中获取测试总时间
    //let timeLong = parent.timeLong;
    //方案2:从sessionStorage中获取测试总时间
    var timeLong = sessionStorage.getItem("timeLong");
    if (timeLong == "" || timeLong == undefined) {
        timeLong = parent.timeLong;
    }
    var scale = xMax / timeLong;
    //求小刻度和大刻度的每一段的实际大小
    var minsize = timeLong / minlen;
    var maxsize = timeLong / maxlen;
    //求小刻度和大刻度的每一段的像素大小
    var minsizepx = minsize * scale;
    var maxsizepx = maxsize * scale;
    //小刻度和大刻度的点集合
    var minpoints = "";
    var maxpoints = "";
    //刻度值
    var text = "";
    var height1 = 4; //上移的刻度长度1
    var height2 = 8; //上移的刻度长度2
    for (var i = 0; i < minlen; i++) {
        minpoints += '<polyline class="XAxis" points="' + (xo + i * minsizepx) + "," + yo + " " + (xo + i * minsizepx) + "," + (yo - height1) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
    }
    //从cookie中获取X轴的最大值和最小值
    let bottomXlimit = $.cookie("bottomXlimit");
    let topXlimit = $.cookie("topXlimit");
    var xScale = "";
    for (var i = 0; i < maxlen; i++) {
        maxpoints += '<polyline class="XAxis" points="' + (xo + i * maxsizepx) + "," + yo + " " + (xo + i * maxsizepx) + "," + (yo - height2) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';

        //X轴的刻度值
        if (bottomXlimit == "" || bottomXlimit == undefined) {
            xScale = parseInt((i * maxsize).toFixed(0));
            //cookie中没有这两个值时添加0和x轴最大值，用于曲线放大后的还原-gy-2018年11月5日
            if (i == 0) {
                $.cookie("bottomXlimit", 0);
                $.cookie("topXlimit", parseInt(timeLong));
            }
        } else {
            xScale = parseInt(bottomXlimit) + parseInt((i * maxsize).toFixed(0));
        }
        //绘制刻度值(注意:此处刻度值偏移了10个像素)
        text += '<text class="xAxisScale" x="' + (xo + i * maxsizepx - 10) + '" y="' + (yo + 20) + '" fill="' + xAxisColor + '">' + xScale + '</text>';
    }

    //添加x轴尾部-gy -2018年11月22日
    var timeScale = sessionStorage.getItem("timeScale");
    let initMax = xo + parseInt((maxlen - 1) * maxsizepx);
    let initMini = xo + parseInt((minlen - 1) * minsizepx);
    let endCount = parseInt((timeScale - parseInt(xScale)) / maxsize);
    if (endCount != 0) {
        for (var j = 1; j <= endCount * 2; j++) {
            minpoints += '<polyline class="XAxis" points="' + (initMini + j * minsizepx) + "," + yo + " " + (initMini + j * minsizepx) + "," + (yo - height1) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
        }
        for (var j = 1; j <= endCount; j++) {
            maxpoints += '<polyline class="XAxis" points="' + (initMax + j * maxsizepx) + "," + yo + " " + (initMax + j * maxsizepx) + "," + (yo - height2) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
            xScale = xScale + parseInt((maxsize).toFixed(0));
            text += '<text class="xAxisScale" x="' + (initMax + j * maxsizepx - 10) + '" y="' + (yo + 20) + '" fill="' + xAxisColor + '">' + xScale + '</text>';
        }
    }
    //添加x轴的头部 -gy -2018年11月22日
    let headCount = parseInt(bottomXlimit / maxsize);
    if (bottomXlimit != 0) {
        for (var i = 1; i <= headCount * 2; i++) {
            minpoints += '<polyline class="XAxis" points="' + (xo - i * minsizepx) + "," + yo + " " + (xo - i * minsizepx) + "," + (yo - height1) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
        }
        for (var i = 1; i <= headCount; i++) {
            maxpoints += '<polyline class="XAxis" points="' + (xo - i * maxsizepx) + "," + yo + " " + (xo - i * maxsizepx) + "," + (yo - height2) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
            xScale = parseInt(bottomXlimit) - parseInt((i * maxsize).toFixed(0));
            text += '<text class="xAxisScale" x="' + (xo - i * maxsizepx - 10) + '" y="' + (yo + 20) + '" fill="' + xAxisColor + '">' + xScale + '</text>';
        }
    }

    //单位
    var unittext = '<text class="xAxisUnit" fill="red" x="' + (xMax - 35) + '"  y="' + (yo + 20) + '" >(min)</text>'
    svg.html(svg.html() + minpoints + maxpoints + text + unittext);
}

//3.2.绘制多个Y轴(x0 y0 开始点 h高度像素)-----middle
function paintMultyYaxis(xo, yo, yMax) {
    //Y轴颜色
    let yAxisColor = "#fff";
    //清空画布
    clearCanvas("myCanvas2");
    //(x0,y0)=(50,470)
    var domAxisList = $("#axisList input");
    var sensorNames = $("#axisList .axisName");
    for (var i = 0; i < axisList.length; i++) {
        //只绘制选中的坐标系
        if (domAxisList[i].checked) {
            var yaxislen = axisList[i].highvalue - axisList[i].lowvalue;
            var step = yaxislen/10; //步长为10
            //获取传感器名称
            let sensorName = sensorNames[i].innerText.trim();
            if (sensorName == "频率") {
                step = yaxislen/10;
            } else if (sensorName == "温度") {
                step = 10;
            } else if (sensorName == "功率因数") {
                step = 0.2;
            } else if (sensorName == "电压") {
                step = 50;
            } else if (sensorName == "功率") {
                step = 50;
            } else if (sensorName == "电流") {
                step = yaxislen/10;
            } else if (sensorName == "耗电量") {
                step = 2;
            } else if (sensorName == "压力") {
                step = 20;
            }
            var yaxisnumber = yaxislen / step;
            //y轴偏移的像素
            var stepPX = (step /yaxislen) * yMax;

            var biglen = 10; //大刻度长度
            ctx2.lineWidth = 0.7; //线条的宽度
            ctx2.strokeStyle = yAxisColor; //线条的颜色
            ctx2.font = "13px 宋体";
            //绘制刻度
            //记录上一次的绘制y轴终点
            var yotemp = yo;
            for (var j = 1; j <= yaxisnumber; j++) {
                ctx2.beginPath(); //开始一条新路径绘制
                ctx2.moveTo(xo, yotemp);
                yotemp = yo - j * stepPX;
                ctx2.lineTo(xo, yotemp);
                ctx2.lineTo(xo + biglen, yotemp);
                //设置字体样式
                ctx2.stroke(); //绘制
                //设置字体填充颜色
                ctx2.font = "13px 宋体";
                ctx2.fillStyle = "#fff";
                //绘制刻度值
                let markvalue = axisList[i].lowvalue + step * j;
                //如果数值>5,则保留整数,<5,保留1位小数
                if (Math.abs(markvalue) > 5) {
                    markvalue = markvalue.toFixed(0);
                } else {
                    markvalue = markvalue.toFixed(1);
                }
                ctx2.fillText(markvalue, xo + biglen, yo - stepPX * j);
            }

            var smalllen = 5; //小刻度长度
            //绘制刻度
            //记录上一次的绘制y轴终点
            var yotemp = yo;
            for (var j = 1; j <= yaxisnumber * 2; j++) {
                ctx2.beginPath(); //开始一条新路径绘制
                ctx2.moveTo(xo, yotemp);
                yotemp = yo - j * stepPX / 2;
                ctx2.lineTo(xo, yotemp);
                ctx2.lineTo(xo + smalllen, yotemp);
                //设置字体样式
                ctx2.stroke(); //绘制
            }
            //绘制y轴最大刻度上的线
            ctx2.beginPath();
            ctx2.moveTo(xo, yotemp);
            ctx2.lineTo(xo, yotemp - 30);
            //设置字体样式
            ctx2.stroke(); //绘制

            //绘制箭头
            // ctx2.beginPath();
            // ctx2.moveTo(xo - smalllen, yo - yMax + smalllen);
            // ctx2.lineTo(xo, yo - yMax-smalllen);
            // ctx2.lineTo(xo + smalllen, yo - yMax + smalllen);
            // ctx2.stroke();

            //设置单位名称
            ctx2.beginPath();
            ctx2.moveTo(xo, yo);
            ctx2.fillStyle = "yellow"; //填充的颜色
            ctx2.fillText("(" + trim(axisList[i].sensorunit) + ")", xo + biglen / 2, yo - yMax + 2 * biglen);
            xo += 35; //右移35px
            ctx2.stroke(); //绘制
        }
    }
}

//3.2.1 清空画布
function clearCanvas(canvasName) {
    var canvas = document.getElementById(canvasName); //选择要擦除的canvas元素
    var context = canvas.getContext('2d'); //获取canvas上下文
    //第一种方法擦除（clearRect方法）
    context.clearRect(0, 0, canvas.width, canvas.height);
//第二种方法擦除（重新设置高宽度）
//canvas.attr('width', canvas.width());
//canvas.attr('height', canvas.height());
}

//3.3绘制网格虚线
function paintDashed(xo, yo, xMax, yMax) {
    //	let svg = $('#svgCurveLines');
    let svg = $('#dottedPortion');
    //1.计算X轴间隔,绘制X轴虚线
    //x轴的段数
    var xPerSize = 20;
    //X轴每一段的间隔
    var xPerLen = xMax / xPerSize;

    //2.计算Y轴间隔,绘制Y轴虚线
    var yPerSize = 10;
    var yPerLen = yMax / yPerSize;

    let axisXDashed = "";
    for (let i = 0; i < yPerSize; i++) {
        let yLen = yRemainder + yPerLen * i;
        let d = "M" + xo + " " + yLen + " l" + xMax + "  0";
        axisXDashed += "<path class='xDashed' stroke-dasharray='5,10' stroke-width='2' stroke='#2E3844' d='" + d + "'/>";
    }

    let axisYDashed = "";
    for (let i = 0; i < xPerSize; i++) {
        let xLen = xo + xPerLen * i;
        let d = "M" + xLen + " 0 l0 " + yo;
        axisYDashed += "<path class='yDashed' stroke-dasharray='5,10' stroke-width='2' stroke='#2E3844' d='" + d + "'/>";
    }
    svg.html(svg.html() + axisXDashed + axisYDashed); //绘制
    //设置全局变量中isShowGrid为true,表示网格虚线已经绘制
    isShowGrid = true;
}

//3.3canvas绘制网格虚线及背景色--gy
function drawGrid(stepx, stepy) {
    //context_gridCanvas.save();//状态的保存
    context_gridCanvas.fillStyle = 'black';
    context_gridCanvas.fillRect(0, 0, context_gridCanvas.canvas.width, context_gridCanvas.canvas.height);
    context_gridCanvas.lineWidth = 0.6; //线条的宽度
    context_gridCanvas.strokeStyle = "#006464"; //线条的颜色
    context_gridCanvas.setLineDash([ 6, 6 ]); //虚线
    if (isShowGrid == true) {
        for (var i = stepx; i < context_gridCanvas.canvas.width; i += stepx) {
            context_gridCanvas.beginPath();
            context_gridCanvas.moveTo(i, 0);
            context_gridCanvas.lineTo(i, context_gridCanvas.canvas.height);
            context_gridCanvas.closePath();
            context_gridCanvas.stroke();
        }
        for (var j = stepy; j < context_gridCanvas.canvas.height; j += stepy) {
            context_gridCanvas.beginPath();
            context_gridCanvas.moveTo(0, j);
            context_gridCanvas.lineTo(context_gridCanvas.canvas.width, j);
            context_gridCanvas.closePath();
            context_gridCanvas.stroke();
        }
        isShowGrid = false;
    } else {
        isShowGrid = true;
    }
    //context_gridCanvas.restore();//状态的恢复

}

//4.绘制传感器对应的曲线-----middle
function paintSvgCurveLine(sensorno) {
    //判断该传感器编号的曲线是否存在,存在则不绘制
    if ($('#svgsensorno' + sensorno).length > 0 && $.cookie("isRepaint") == "false") {
        return;
    }
    if ($.cookie("isRepaint") == "true") {
        //消除原先绘制的曲线
        let leftsvgsensorno = $('#svgsensorno' + sensorno);
        leftsvgsensorno.remove();
    }
    //1.根据传感器编号查询该传感器的所有测试数据
    //方案1:从页面缓存中获取传感器的值
    // let sensorInfo = parent.sensorValues.filter((s) => {
    //     return s.sensorno == sensorno;
    // });
    // if(sensorInfo==undefin||sensorInfo.length==0){
    //     console.log("页面缓存中没用找到"+sensorno+"的信息");
    //     //return;
    // }else{
    //     sensorInfo=sensorInfo[0].sensorinfo;
    // }

    //方案2:从sessionStorage中获取传感器的值
    let sensor = sessionStorage.getItem("sensorno" + sensorno + "Values");
    let sensorInfo = JSON.parse(sensor);
    if (sensorInfo == null) {
        //根据传感器编号查询传感器数据
        sensorInfo = parent.getSensorDataBySensorNo(sensorno);
    }

    let sensorValue = sensorInfo.sensorvalues;
    let relativetime = sensorInfo.relativetime;
    let totaltime = sensorInfo.totaltime;
    let coordinateno = sensorInfo.coordinateno;
    if (coordinateno == undefined) {
        console.log("sessionStorage中的sensorno1Values出错");
        return;
    }
    //2.根据坐标系编号查询该传感器所在坐标系的上下限
    let coordinateInfo = sessionStorage.getItem("coordinateno" + coordinateno);
    let highvalue = JSON.parse(coordinateInfo).highvalue;
    let lowvalue = JSON.parse(coordinateInfo).lowvalue;
    let yRange = highvalue - lowvalue;
    //3.从session Storage中获取颜色
    let sensorColor = sessionStorage.getItem( sensorno+'color');
    sensorColor = parent.getColorFromSessionStorage(sensorColor);
    //4.绘制曲线
    let sensorValueLength = sensorValue.length;
    step = 5; //初始化步长
    var res = "";
    var line = '';
    //sensorValueLength
    for (let i = 0; i < sensorValueLength; i += step) {
        if (2 < 1) {
            //4.1坐标轴没有负值

        } else {
            //4.2坐标轴有负值
            if (lowvalue < 0) {
                lowvalue = Math.abs(lowvalue);
            }
            //从cookie中获取X轴的最大值和最小值
            let bottomXlimit = $.cookie("bottomXlimit");
            let topXlimit = $.cookie("topXlimit");
            let time = topXlimit - bottomXlimit;
            let x = "";
            //若cookie中的最大值和最小值不存在,则绘制所有
            if (bottomXlimit == "" || topXlimit == "" || bottomXlimit == undefined || topXlimit == undefined) {
                x = x0 + parseInt(relativetime[i]) * xMax / totaltime;
            } else if (parseInt(relativetime[i]) < bottomXlimit) {
                //x轴的时间值小于横坐标最小值:绘制原点前边的图像
                x = x0 - parseInt(bottomXlimit - relativetime[i]) * xMax / time;
            } else if (parseInt(relativetime[i]) > topXlimit) {
                //X的值大于横坐标的最大值,则不绘制：绘制右边的图像
                x = x0 + (parseInt(relativetime[i]) - bottomXlimit) * xMax / time;
            } else {
                totaltime = topXlimit - bottomXlimit;
                //求X轴像素的偏移量
                //let xPixel = bottomXlimit * xMax / totaltime;
                x = x0 + (parseInt(relativetime[i]) - bottomXlimit) * xMax / totaltime;
                //				continue;
            }
            //计算y轴像素的公式为:   y轴像素/y轴总像素=|下限|+y的值/(上限-下限)
            let y = y0 - (parseInt(sensorValue[i]) + lowvalue) * yMax / yRange;
            if (sensorno == 65){
                console.log("highvalue:"+highvalue);
                console.log("lowValue:"+lowvalue);
                console.log("coordinateno"+coordinateno);
                console.log("y0:"+ y0);
                console.log("ymax:"+yMax);
                console.log("y:"+y);
                console.log("yRange:"+yRange);
                console.log("lowValue:"+lowvalue);
                console.log(sensorValue[i]);
            }

            line += x + "," + y + " ";
        }
    }
    res += '<polyline id="svgsensorno' + sensorno + '"' + 'points="' + line + '" style="fill:none;stroke:' + sensorColor + ';stroke-width:1" />';
    $("#svgCurveLines").html($("#svgCurveLines").html() + res); //绘制

    //设置拖动方向，只按x轴方向拖动
    $("#svgCurveLines").panzoom({
        disableYAxis : true
    });
    //绘制完毕设置为false
    $.cookie("isRepaint", "false");
}

//4.获取鼠标的位置
function getLocation(x, y) {
    var bbox = canves_js.getBoundingClientRect();
    return {
        x : (x - bbox.left) * (canves_js.width / bbox.width),
        y : (y - bbox.top) * (canves_js.height / bbox.height)
    };
}

//4.绘制y轴虚线
function drawHorizontalLine(y) {
    context.beginPath();
    context.strokeStyle = '#fff';
    //绘制虚线
    context.setLineDash([ 10, 5 ]);
    //context.moveTo(0, y);
    //context.lineTo(canves_js.width, y);
    context.moveTo(x0, y);
    context.lineTo(xMax, y);
    context.stroke();
    context.closePath();
}

//4.绘制X轴虚线
function drawVerticalLine(x) {
    context.beginPath();
    context.strokeStyle = '#fff';
    context.moveTo(x, 0);
    //context.lineTo(x, canves_js.height);
    context.lineTo(x, y0);
    context.stroke();
    context.closePath();
}

//4.绘制提示信息
function drawPointInfo(x, y, xAxisValues) {
    context.beginPath();
    context.strokeStyle = '#fff';
    context.fillStyle = "yellow"; //填充的颜色
    context.fillText("" + xAxisValues + "min", x + 10, y + 10);
    context.stroke();
    context.closePath();
}

//4.鼠标移入时的触发事件(绘制随鼠标移动的十字线)
//document.onMOUSEMOVE = mouseMove;
document.addEventListener('mousemove', mouseMove);

function mouseMove(e) {
    context.clearRect(0, 0, canves_js.width, canves_js.height);
    var location = getLocation(e.clientX, e.clientY);
    //如果鼠标移动到非法区域,则取消绘制
    if (location.x < x0 || location.y > y0 || location.x > xMax) {
        return;
    }
    drawHorizontalLine(location.y);
    drawVerticalLine(location.x);

    //计算当前鼠标停留的x轴时间和Y轴的值
    //公式:最小时间+当前时间/总测试时间=当前像素/总像素
    //当前鼠标停留的X轴值
    let timeLong = sessionStorage.getItem("timeLong");
    let bottomXlimit = $.cookie('bottomXlimit');
    let xAxisValues = "";
    if (bottomXlimit == undefined) {
        xAxisValues = parseInt(((location.x - x0) * timeLong / xMax).toFixed(0));
    } else {
        xAxisValues = parseInt(((location.x - x0) * timeLong / xMax).toFixed(0)) + parseInt(bottomXlimit);
    }
    //过滤x的不合法值
    if (xAxisValues <= 0) {
        xAxisValues = 0;
    }
    //绘制提示信息
    drawPointInfo(location.x, location.y, xAxisValues);
    //根据曲线的移动实时显示传感器的值
    parent.showSensorValues(xAxisValues);

}

//4.根据x轴值获取y轴值(请求后台获取)
function getYAxisValue(sensorno, xAxisValue) {
    let yAxisValue = "";
    let labcode = $.cookie('labcode');
    let primarykey = $.cookie('nowprimarykey');
    $.ajax({
        type : "get",
        async : false, //设置为同步请求,防止接收不到数据
        url : top.basePath +config.bxxs.apiPath+ "/TestData/getYAxisValue",
        data : {
            labcode : labcode,
            primaryKey : primarykey,
            sensorNo : sensorno,
            xAxisValue : xAxisValue
        },
        success : function(msg) {
            yAxisValue = msg;
        },
        error : function(e) {
            alert("网页发生错误：", e, "error");
        }
    });
    return yAxisValue;
}

//4.根据x轴值获取y轴值(从sessionStorage中获取)
function getYAxisValueFromSessionStorage(sensorno, xAxisValue) {
    let yAxisValue = "";
    let sensorInfo = sessionStorage.getItem("sensorno" + sensorno + "Values");
    if (sensorInfo != undefined) {
        let relativetime = JSON.parse(sensorInfo).relativetime;
        let lastIndex = relativetime.indexOf(xAxisValue);
        let sensorvalues = JSON.parse(sensorInfo).sensorvalues;
        if (lastIndex != -1) {
            yAxisValue = sensorvalues[lastIndex];
        }
    }
    return yAxisValue;
}

//5.根据传感器号获取传感器对应的颜色(从sessionStorage中获取)
function getAxisColorFromSessionStorage(sensorno) {
    let AxisColors = "";
    let sensorColors = sessionStorage.getIteam(sensorno + "color");
    if (sensorColors != undefined) {
        //AxisColors=JSON.parse(sensorColors).sensorColor;
        AxisColors = sensorColors;
    }
    return AxisColors;
}

//**************************工具箱*******************************
//1.测试元数据(铭牌信息)点击事件
function showMataInfoWindow() {
    //获取当前页面的宽度
    //yyi 修改
    /*let labcode = "Haierrefrigerator20151214";
    let testunitno = "1";
    let primaryKey = "2017-11-1611:17:211";*/
    let labcode = $.cookie('labcode'); //实验室编码
    let primaryKey = $.cookie('nowprimarykey'); //primarykey
    let testunitno = $.cookie('nowtestunitno'); //testunitno
    let url = "http://localhost/consumer/CurveInfoAPI/getTestProdInfo?labcode=" + labcode + "&primaryKey=" + primaryKey + "&testunitno=" + testunitno;
    layer.open({
        title : "铭牌信息",
        type : 2,
        area : [ '600px', '550px' ],
        fixed : false, //不固定
        maxmin : true,
        offset : '50px', //设置窗口的位置
        //content : [ url, 'no' ] //滚动条 禁止
        content:["../../html/curveData/layer/middle_metaDataLayer.html",'no']
    });
}

//2.传感器设置
function sensorConfig() {
    //获取当前页面的宽度
    //yyi 修改
    /*let labcode = "Haierrefrigerator20151214";
    let testunitno = "1";
    let primaryKey = "2017-11-1611:17:211";*/
    let labcode = $.cookie('labcode'); //实验室编码
    let primaryKey = $.cookie('nowprimarykey'); //primarykey
    let testunitno = $.cookie('nowtestunitno'); //testunitno
    let url = "http://localhost/consumer/CurveInfoAPI/updateSensorsByPrimaryKey?labcode=" + labcode + "&primaryKey=" + primaryKey + "&testunitno=" + testunitno;
    layer.open({
        title : "传感器设置",
        type : 2,
        area : [ '1000px', '590px' ],
        fixed : false, //不固定
        maxmin : true,
        offset : '50px', //设置窗口的位置
        content : [ "../../html/curveData/layer/middle_sensorConfigLayer.html", 'no' ], //滚动条 禁止
        btn : [ '保存', '关闭' ],
        yes : function(index, layero) {
            //调用 middle_sensorConfigLayer.jsp中的方法
            var iframeWin = window[layero.find('iframe')[0]['name']];
            var flag = iframeWin.updateSensorsData();
            if (flag == "success") {
                layer.msg('保存成功', {
                    anim : 0,
                    time : 1000,
                    end : function() {
                        layer.close(index);
                    }
                });
            }
            if (flag == "error") {
                layer.msg('保存失败', {
                    anim : 0,
                    time : 1000,
                    end : function() {
                        layer.close(index);
                    }
                });
            }
        }
    });
}

//3.曲线显示范围点击事件
function showCurveRangeWindow() {
    //获取当前页面的宽度
    let labcode = $.cookie('labcode'); //实验室编码
    let primaryKey = $.cookie('nowprimarykey'); //primarykey
    let testunitno = $.cookie('nowtestunitno'); //testunitno
    /*let labcode = "Haierrefrigerator20151214";
    let testunitno = "1";
    let primaryKey = "2017-11-1611:17:211";*/
    let url = "page/CurveRangeLayer?labcode=" + labcode + "&primaryKey=" + primaryKey + "&testunitno=" + testunitno;
    layer.open({
        title : "曲线显示范围",
        type : 2,
        area : [ '600px', '300px' ],
        fixed : false, //不固定
        maxmin : true,
        offset : '100px', //设置窗口的位置
        content : [ "../../html/curveData/layer/middle_curveRangeLayer.html", 'no' ] //滚动条 禁止
    });
}

//3.设置曲线显示范围
function setXAxisRange(bottomXlimit, topXlimit) {
    //更新全局变量和sessionStorage中的测试总时间
    parent.timeLong = topXlimit - bottomXlimit;
    sessionStorage.setItem("timeLong", topXlimit - bottomXlimit);
    //设置重新绘制
    $.cookie("isRepaint", "true");
    //1.重新绘制X轴
    paintXaxis(x0, y0, xMax);
    //2.重新绘制曲线
    let sensorArray = parent.getAllSelectSeneor();
    for (j = 0, len = sensorArray.length; j < len; j++) {
        paintSvgCurveLine(sensorArray[j]);
    }
}

//4.温度统计范围按钮点击事件
var lineLeft = null;
var lineRight = null;

function temperatureRange() {
    //左右侧连接点
    let leftPoint = {
        X : 100,
        Y : 100
    };
    let rightPoint = {
        X : 400,
        Y : 100
    };
    // 初始化zrender
    var div_zrender = document.getElementById('zrender');
    var zr = zrender.init(div_zrender);

    zr.on('mousedown', function() {
        isMouseDown = true;
    });
    zr.on('mouseup', function() {
        isMouseDown = false;
    });

    let yAxisMax = y0;

    lineLeft = new zrender.Line({
        shape : {
            x1 : 100,
            y1 : 0,
            x2 : 100,
            y2 : yAxisMax
        },
        style : {
            stroke : '#fff',
            lineDash : [ 7, 7 ]
        },
        //设置虚线可拖动
        draggable : true
    }).on('mousemove', function(event) {
        lineVertical.setShape({
            x1 : event.offsetX,
        });
        lineLeft.shape.x1 = event.offsetX;
        lineLeft.shape.x2 = event.offsetX;
    });
    zr.add(lineLeft);

    lineRight = new zrender.Line({
        shape : {
            x1 : 400,
            y1 : 0,
            x2 : 400,
            y2 : yAxisMax
        },
        style : {
            stroke : '#fff',
            lineDash : [ 7, 7 ]
        },
        //设置虚线可拖动
        draggable : true
    }).on('mousemove', function(event) {
        lineVertical.setShape({
            x2 : event.offsetX
        });
        lineRight.shape.x1 = event.offsetX;
        lineRight.shape.x2 = event.offsetX;
    });
    zr.add(lineRight);

    //中间的连接线
    var lineVertical = new zrender.Line({
        shape : {
            x1 : leftPoint.X,
            y1 : leftPoint.Y,
            x2 : rightPoint.X,
            y2 : rightPoint.Y
        },
        style : {
            stroke : '#fff',
            lineDash : [ 7, 7 ]
        },
        //设置虚线可拖动
        draggable : false
    });
    zr.add(lineVertical);
}

//6.数据列表点击事件
function showDataList() {
    let labcode = $.cookie('labcode'); //实验室编码
    let primarykey = $.cookie('nowprimarykey'); //primarykey
    //let url = "page/DataListLayer?labcode=" + labcode + "&primarykey=" + primarykey;
    let url = "";
    layer.open({
        title : "数据列表",
        type : 2,
        area : [ '900px', '550px' ],
        fixed : false, //不固定
        maxmin : true,
        content : [ "../../html/curveData/layer/middle_dataListLayer.html", 'no' ] //滚动条 禁止
    });
}

//7.统计值点击事件
function showStatistics() {
    //yyi 写死使用
    console.log("进入showStatistics()");
    /*let  labcode = "Haierrefrigerator20151214";
    let primarykey = "2017-11-1611:17:211";*/
    let labcode = $.cookie('labcode'); //实验室编码
    let primarykey = $.cookie('nowprimarykey'); //primarykey
    if (lineLeft == null) {
        sweetAlert("警告", "请先选择温度统计范围", "warning");
        return;
    }
    //获取时间范围
    //1.获取两线的时间点
    let leftX = getRealXValue(lineLeft.shape.x1, window.x0, window.xMax);
    let rightX = getRealXValue(lineRight.shape.x1, window.x0, window.xMax);
    //2.存到session中，供弹出层使用
    $.session.set('statisticalStartTime', leftX);
    $.session.set('statisticalEndTime', rightX);

    //let url = "page/StatisticsLayer?labcode=" + labcode + "&primarykey=" + primarykey;
    layer.open({
        title : "统计值",
        type : 2,
        area : [ '900px', '550px' ],
        fixed : false, //不固定
        maxmin : true,
        content : [ "../../html/curveData/layer/middle_statisticsLayer.html", 'no' ] //滚动条 禁止
    });
}

//8.曲线自适应点击事件
function fitCurveLine() {
    showNewCurve();
}

//9.清除标记点击事件
function clearFlag() {
    //1.清除曲线
    // 初始化zrender
    var zr = zrender.init(document.getElementById('zrender'));
    //2.清除cookie和sessionStorage中的标志位
    zr.clear();
    //重新设置监听,绘制十字
    document.addEventListener('mousemove', mouseMove);
}

//10.导出表格
function exportData() {
    let labCode = $.cookie('labcode');
    let primarykey = $.cookie('nowprimarykey');
    let testUnitNo = $.cookie('nowtestunitno');
    //yyi
   /* let labCode="Haierrefrigerator20151214";
    let primarykey="2017-11-1611:17:211";
    let testUnitNo="1";*/

    //1.选择了时间段
    if (lineLeft != null || lineRight != null) {
        let startDate = getRealXValue(lineLeft.shape.x1, window.x0, window.xMax);
        let endDate = getRealXValue(lineRight.shape.x1, window.x0, window.xMax);
        //2.提交数据
        //window.location.href = "http://localhost/consumer/CurveInfoAPI/exportTestData?labCode=" + labCode + "&primarykey=" + primarykey + "&testUnit=" + testUnitNo + "&startDate=" + startDate + "&endDate=" + endDate;
        window.location.href = "http://localhost:8001/mysqlapi/TestData/exportTestData?labCode=" + labCode + "&primarykey=" + primarykey + "&testUnit=" + testUnitNo + "&startDate=" + startDate + "&endDate=" + endDate;
        //		$.ajax({
        //			type : "get",
        //			url : "api/TestData/exportTestData",
        //			data : "labCode=" + labCode + "&primarykey=" + primarykey + "&testUnit=" + testUnitNo + "&startDate=" + startDate + "&endDate=" + endDate,
        //			success : function(msg) {}
        //		});
    } else {
        //window.location.href = "http://localhost/consumer/CurveInfoAPI/exportTestData?labCode=" + labCode + "&primarykey=" + primarykey + "&testUnit=" + testUnitNo;
        window.location.href = "http://localhost:8001/mysqlapi/TestData/exportTestData?labCode=" + labCode + "&primarykey=" + primarykey + "&testUnit=" + testUnitNo;
    }

}

//11.打印预览
function printPreview() {
    let layerid = layer.msg('加载中', {
        icon : 16,
        shade : 0.4,
        time : false //取消自动关闭
    });
    let topBasePath = getTopBasePath(top.basePath);
    //获取当前页面的宽度
    //yyi 注释
    let labcode = $.cookie('labcode'); //实验室编码
    let primarykey = $.cookie('nowprimarykey'); //primarykey
    let testunitno = $.cookie('nowtestunitno'); //testunitno
   /* let labcode = "Haierrefrigerator20151214";
    let testunitno = "1";
    let primarykey = "2017-11-1611:17:211";*/
    //方式1:抓取页面中的数据,保存在sessionStorage中
    //方式2:抓取页面中的数据,保存在redis中
    //2.1抓取页面中的div数据,并保存到redis中
    var cruveData = $("#curveArea").html();
    let url =  "http://localhost/consumer/CurveInfoAPI/putDivCruveData";

    //putImageDataToRedis(url, primarykey, cruveData);
    //2.2抓取页面中的canves数据,并保存到redis中
    url = "http://localhost/consumer/CurveInfoAPI/putCanvasCruveData";
    var canvas_imgData = ctx.getImageData(0, 0, xMax, yMax);
    //window.localStorage.canvas_imgData=JSON.stringify(canvas_imgData);
    //putImageDataToRedis(url,primarykey,canvas_imgData);
    var canva2_imgData = ctx2.getImageData(0, 0, xMax, yMax);
    //window.localStorage.canva2_imgData=JSON.stringify(canva2_imgData);
    //putImageDataToRedis(url,primarykey,canva2_imgData);
    var gridCanvas_imgData = ctx_gridCanvas.getImageData(0, 0, xMax, yMax);
    //window.localStorage.gridCanvas_imgData=JSON.stringify(gridCanvas_imgData);
    //putImageDataToRedis(url,primarykey,gridCanvas_imgData);
    var image = new Image();
    var childCanvas;
    //获取当前窗口名称
    var parentName = window.name;
    let pageWidth = $(window).width();
    html2canvas($("#curveArea"), {
        //设置为同步执行
        async : false,
        // $("body")是你要复制生成canvas的区域，可以自己选
        onrendered : function(canvas) {
            image.src = canvas.toDataURL("image/png");
            $("body").append(canvas);
            childCanvas = canvas;
        },
        width : pageWidth,
        height : canves2_js.height //使用canvas2的高度
    })

    //2.3抓取左侧的传感器列表数据,并保存在redis中
    var letfSensorData = parent.getLeftSensorData();
    url = "http://localhost/consumer/CurveInfoAPI/putLeftSensorData";
    putImageDataToRedis(url, primarykey, letfSensorData);

    layer.close(layerid); //手动关闭

    //let layer_url = "page/PrintPreviewLayer?labcode=" + labcode + "&primarykey=" + primarykey + "&testunitno=" + testunitno + "&parentName=" + parentName;
    var index = top.layer.open({
        title : "打印预览",
        type : 2,
        area : [ '800px', '650px' ],
        fixed : false, //不固定
        maxmin : true,
        offset : '50px', //设置窗口的位置
        //content : [ layer_url, 'no' ] //滚动条禁止
        content : [ "../../html/curveData/layer/middle_printPreviewLayer.html", 'yes' ], //滚动条显示
        success : function(layero, index) {
            //注意:一定要通过浏览器查看一下iframe父子页面的层级关系!
            //注意:一定要通过浏览器查看一下iframe父子页面的层级关系!
            //注意:一定要通过浏览器查看一下iframe父子页面的层级关系!
            setTimeout(function() {
                console.log("父子页面传递数据");
                var body = top.layer.getChildFrame('body', index); //建立父子联系
                var iframeWin = window[layero.find('iframe')[0]['name']];
                var printContent = body.find('#printContent');
                printContent.empty();
                printContent.append(childCanvas);
            }, 2000);


        }
    });
    top.layer.full(index);
}
//11.将页面中的数据保存在redis中
function putImageDataToRedis(url, primarykey, cruveData) {
    $.ajax({
        type : "get",
        async : false, //设置为同步请求,防止接收不到数据
        url : url,
        data : {
            primaryKey : primarykey,
            cruveData : cruveData
        },
        success : function(msg) {
            if (msg == "success") {
                console.log("曲线数据保存成功");
            } else {
                console.log("曲线数据保存失败");
            }
        },
        error : function(e) {
            alert("网页发生错误：", e, "error");
        }
    });
}


//*********************曲线右击菜单*******************************
//1.放大曲线
var zoomLeftLine;
var zoomRightLine;
var zoomInHistory = new Array();
var initBottomXlimit;
var initTopXlimit;
var initTimeLong;
function zoomIn() {
    var zrenders = document.getElementById("zrender");
    var zr = zrender.init(zrenders);
    //不放大的情况
    if (isZoomIn) {
        isZoomIn = false;
        //取消拖拽事件
        $('#zrender').attr('draggable', 'false');
    } else {
        //开启拖拽
        $('#zrender').attr('draggable', 'true');
        //放大的情况
        isZoomIn = true;
        //拖拽开始，绘制左侧线
        zrenders.ondragstart = function(event) {
            addLeftLine(event, zr);
        }
        //拖拽中，绘制右侧线
        zrenders.ondrag = function(event) {
            //清空十字绘制
            document.removeEventListener('mousemove', mouseMove);
            context.clearRect(0, 0, canves_js.width, canves_js.height);
            //绘制右线
            addRightLine(event, zr);
        }
        //拖拽结束，获取数据范围
        zrenders.ondragend = function(event) {
            //获取两线的时间点
            let leftX = getRealXValue(zoomLeftLine.shape.x1, window.x0, window.xMax);
            let rightX = getRealXValue(zoomRightLine.shape.x1, window.x0, window.xMax);

            //获取先前的上下限并更新为放大范围
            //如果是首次放大，那么记录放大前的上下限以及timeLong,供还原时使用
            if (!isZoomedIn) {
                initBottomXlimit = $.cookie("bottomXlimit");
                initTopXlimit = $.cookie("topXlimit");
                initTimeLong = sessionStorage.getItem("timeLong");
                isZoomedIn = true;
            } else {
                var record = new Object();
                record.bottomXlimit = $.cookie("bottomXlimit");
                record.preTopXlimit = $.cookie("topXlimit");
                record.preTimeLong = sessionStorage.getItem("timeLong");
                zoomInHistory.push(record);
                isZoomedIn = true;
            }
            $.cookie("bottomXlimit", leftX);
            $.cookie("topXlimit", rightX);
            let timeLong = parseInt(rightX) - parseInt(leftX);
            sessionStorage.setItem("timeLong", timeLong);

            //取消放大范围选取两条线
            zr.remove(zoomLeftLine);
            zr.remove(zoomRightLine);

            //重绘x轴
            zoomX(leftX, rightX);
            //重绘曲线
            let sensorArray = parent.getAllSelectSeneor();
            for (j = 0, len = sensorArray.length; j < len; j++) {
                $.cookie("isRepaint", "true");
                paintSvgCurveLine(sensorArray[j]);
            }
            //还原十字绘制
            document.addEventListener('mousemove', mouseMove);
        }

    }
}
//添加左侧线 gy 2018年10月26日
function addLeftLine(e, zr) {
    //1.获取鼠标的位置
    var location = getLocation(e.clientX, e.clientY);
    //如果鼠标移动到非法区域,则取消绘制
    if (location.x < x0 || location.y > y0 || location.x > xMax) {
        return;
    }

    zoomLeftLine = new zrender.Line({
        shape : {
            x1 : location.x,
            y1 : 0,
            x2 : location.x,
            y2 : 1000
        },
        style : {
            stroke : '#fff'
        },
        //设置虚线可拖动
        draggable : false
    })
    zr.add(zoomLeftLine);
}
//添加右线 gy 2018年10月26日
function addRightLine(e, zr) {
    //1.获取鼠标的位置
    var location = getLocation(e.clientX, e.clientY);
    //如果鼠标移动到非法区域,则取消绘制
    if (location.x < x0 || location.y > y0 || location.x > xMax) {
        return;
    }
    //绘制时间提示
    context.clearRect(0, 0, canves_js.width, canves_js.height);
    var location = getLocation(e.clientX, e.clientY);

    let timeLong = sessionStorage.getItem("timeLong");
    let bottomXlimit = $.cookie('bottomXlimit');
    let xAxisValues = "";
    if (bottomXlimit == undefined) {
        xAxisValues = parseInt(((location.x - x0) * timeLong / xMax).toFixed(0));
    } else {
        xAxisValues = parseInt(((location.x - x0) * timeLong / xMax).toFixed(0)) + parseInt(bottomXlimit);
    }
    //过滤x的不合法值
    if (xAxisValues <= 0) {
        xAxisValues = 0;
    }
    //绘制提示信息
    drawPointInfo(location.x, location.y, xAxisValues);

    if (zoomRightLine != "" && zoomRightLine != null) {
        zr.remove(zoomRightLine);
    }
    zoomRightLine = new zrender.Line({
        shape : {
            x1 : location.x,
            y1 : 0,
            x2 : location.x,
            y2 : 1000
        },
        style : {
            stroke : '#fff'
        },
        draggable : true
    });
    zr.add(zoomRightLine);
}
//绘制X轴放大
function zoomX(startTime, endTime) {
    //1.清空X轴刻度
    $(".xAxisScale").remove();

    //2.重绘X轴刻度
    var minlen = 20;
    var maxlen = 10;
    let timeLong = parseInt(endTime) - parseInt(startTime);
    var scale = xMax / timeLong;
    //求小刻度和大刻度的每一段的实际大小
    var minsize = timeLong / minlen;
    var maxsize = timeLong / maxlen;
    //求小刻度和大刻度的每一段的像素大小
    var minsizepx = minsize * scale;
    var maxsizepx = maxsize * scale;
    //小刻度和大刻度的点集合
    var minpoints = "";
    var maxpoints = "";
    //刻度值
    var text = "";
    var height1 = 4; //上移的刻度长度1
    var height2 = 8; //上移的刻度长度2
    let xAxisColor = "#fff";
    for (var i = 0; i < minlen; i++) {
        minpoints += '<polyline class="XAxis" points="' + (x0 + i * minsizepx) + "," + y0 + " " + (x0 + i * minsizepx) + "," + (y0 - height1) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
    }
    var xScale = "";
    for (var i = 0; i < maxlen; i++) {
        maxpoints += '<polyline class="XAxis" points="' + (x0 + i * maxsizepx) + "," + y0 + " " + (x0 + i * maxsizepx) + "," + (y0 - height2) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
        //X轴的刻度值
        xScale = parseInt(startTime) + parseInt((i * maxsize).toFixed(0));
        //绘制刻度值(注意:此处刻度值偏移了10个像素)
        text += '<text class="xAxisScale" x="' + (x0 + i * maxsizepx - 10) + '" y="' + (y0 + 20) + '" fill="' + xAxisColor + '">' + xScale + '</text>';
    }
    var bottomXlimit = $.cookie("bottomXlimit");
    var topXlimit = $.cookie("topXlimit");
    //添加x轴尾部-gy -2018年11月22日
    var timeScale = sessionStorage.getItem("timeScale");
    let initMax = x0 + parseInt((maxlen - 1) * maxsizepx);
    let initMini = x0 + parseInt((minlen - 1) * minsizepx);
    let endCount = parseInt((timeScale - parseInt(xScale)) / maxsize);
    if (endCount != 0) {
        for (var j = 1; j <= endCount * 2; j++) {
            minpoints += '<polyline class="XAxis" points="' + (initMini + j * minsizepx) + "," + y0 + " " + (initMini + j * minsizepx) + "," + (y0 - height1) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
        }
        for (var j = 1; j <= endCount; j++) {
            maxpoints += '<polyline class="XAxis" points="' + (initMax + j * maxsizepx) + "," + y0 + " " + (initMax + j * maxsizepx) + "," + (y0 - height2) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
            xScale = xScale + parseInt((maxsize).toFixed(0));
            text += '<text class="xAxisScale" x="' + (initMax + j * maxsizepx - 10) + '" y="' + (y0 + 20) + '" fill="' + xAxisColor + '">' + xScale + '</text>';
        }
    }
    //添加x轴的头部 -gy -2018年11月22日
    let headCount = parseInt(bottomXlimit / maxsize);
    if (bottomXlimit != 0) {
        for (var i = 1; i <= headCount * 2; i++) {
            minpoints += '<polyline class="XAxis" points="' + (x0 - i * minsizepx) + "," + y0 + " " + (x0 - i * minsizepx) + "," + (y0 - height1) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
        }
        for (var i = 1; i <= headCount; i++) {
            maxpoints += '<polyline class="XAxis" points="' + (x0 - i * maxsizepx) + "," + y0 + " " + (x0 - i * maxsizepx) + "," + (y0 - height2) + " " + '" style="fill:none;stroke:' + xAxisColor + ';stroke-width:1" />';
            xScale = parseInt(bottomXlimit) - parseInt((i * maxsize).toFixed(0));
            text += '<text class="xAxisScale" x="' + (x0 - i * maxsizepx - 10) + '" y="' + (y0 + 20) + '" fill="' + xAxisColor + '">' + xScale + '</text>';
        }
    }
    //单位
    var unittext = '<text class="xAxisUnit" fill="red" x="' + (xMax - 35) + '"  y="' + (y0 + 20) + '" >(min)</text>'
    let svg = $('#svgCurveLines');
    svg.html(svg.html() + minpoints + maxpoints + text + unittext);
}

//曲线放大还原-gy-2018年11月2日
function zoomInRestore() {
    //	isZoomIn = false;
    isZoomedIn = false;
    //1.还原上下限和timeLong
    $.cookie("bottomXlimit", initBottomXlimit);
    $.cookie("topXlimit", initTopXlimit);
    sessionStorage.setItem("timeLong", initTimeLong);

    //2.重绘x轴
    paintXaxis(x0, y0, xMax);

    //3.重绘曲线
    let sensorArray = parent.getAllSelectSeneor();
    for (j = 0, len = sensorArray.length; j < len; j++) {
        $.cookie("isRepaint", "true");
        paintSvgCurveLine(sensorArray[j]);
    }
}
//曲线还原上一次放大-gy-2018年11月2日
function lastZoomIn() {
    //1.还原上下限和timeLong
    var preZoomIn = zoomInHistory.pop();
    if (preZoomIn != null) {
        $.cookie("bottomXlimit", preZoomIn.bottomXlimit);
        $.cookie("topXlimit", preZoomIn.preTopXlimit);
        sessionStorage.setItem("timeLong", preZoomIn.preTimeLong);
        //2.重绘x轴
        zoomX(preZoomIn.bottomXlimit, preZoomIn.preTopXlimit);
        //3.重绘曲线
        let sensorArray = parent.getAllSelectSeneor();
        for (j = 0, len = sensorArray.length; j < len; j++) {
            $.cookie("isRepaint", "true");
            paintSvgCurveLine(sensorArray[j]);
        }
    } else {
        zoomInRestore();
    }
}

//2.曲线移动
function curveMove() {
    //判断是否进行拖拽
    if (isDraggle) {
        isDraggle = false;
        //不拖拽的情况
        //恢复svg和两个canvas的z-index以及背景色
        $("#svgCurveLines").css({
            "z-index" : "auto"
        })
        $("#myCanvas").css({
            "z-index" : 999
        })
        $("#myCanvas2").css({
            "z-index" : 99
        })
        $("#zrender").css({
            "z-index" : 9999
        })
        //恢复十字绘制
        document.addEventListener('mousemove', mouseMove);
    } else {
        isDraggle = true;
        //拖拽的情况
        //1.调整svg和两个canvas的z-index
        $("#svgCurveLines").css({
            "z-index" : 2
        })
        $("#myCanvas").css({
            "z-index" : -1
        })
        $("#myCanvas2").css({
            "z-index" : -2
        })
        $("#zrender").css({
            "z-index" : -3
        })

        //2.取消十字
        //取消监听事件
        document.removeEventListener('mousemove', mouseMove);
        //清空已经绘制的十字
        context.clearRect(0, 0, canves_js.width, canves_js.height);
    }

}

//3.瞬时数据标注
function shunRemark() {
    //取消监听事件
    document.removeEventListener('mousemove', mouseMove);
    // 清空已经绘制的十字
    context.clearRect(0, 0, canves_js.width, canves_js.height);
    // 初始化zrender
    var div_zrender = document.getElementById('zrender');
    var zr = zrender.init(div_zrender);
    let yAxisMax = y0;
    let xPosition = 300;
    let line = new zrender.Line({
        shape : {
            x1 : xPosition,
            y1 : 0,
            x2 : xPosition,
            y2 : yAxisMax
        },
        style : {
            stroke : '#fff',
            lineDash : [ 7, 7 ]
        },
        //设置虚线可拖动
        draggable : true
    }).on('mousemove', function(event) {
        line.shape.x1 = event.offsetX;
        line.shape.x2 = event.offsetX;
        if (event.offsetX >= x0 && event.offsetX <= xMax) {
            shunText(event.offsetX, event.offsetY, zr);
        }

    });
    zr.add(line);
}

//3.根据x轴的实际值查询该点所有的传感器值,并进行文本标注
var text = new Array();
function shunText(x, y, zr) {
    //清空Text显示
    var sensorArray = parent.getAllSelectSeneor();
    for (j = 0, len = sensorArray.length; j < len; j++) {
        if (text[j] != null && text[j] != "") {
            zr.remove(text[j]);
        }
    }
    //从sessionStorage中获取传感器数组中所有的值,并进行遍历显示
    for (j = 0, len = sensorArray.length; j < len; j++) {
        //根据x轴的坐标值和传感器编号获取y的值(带单位)
        //var YAxisValues = getYAxisValueFromSessionStorage(sensorArray[j], x);
        var YAxisValues = parent.getSensorValues(x, sensorArray[j]);
        var AxisColors = parent.getColorFromSessionStorage("sensorColor color" + sensorArray[j]);
        text[j] = new zrender.Text({
            style : {
                fontSize : '15',
                text : sensorArray[j] + ':' + YAxisValues,
                textFill : AxisColors,
            },
        });
        text[j].attr('position', [ x, 150 + j * 25 ]);
        zr.add(text[j]);
    }
}


//4.显示网格
//function showGrid() {
//	if (isShowGrid) {
//		let xDashed = $('.xDashed');
//		let yDashed = $('.yDashed');
//		xDashed.remove();
//		yDashed.remove();
//		isShowGrid = false;
//	} else {
//		//绘制网格虚线
//		paintDashed(x0, y0, xMax, yMax);
//	}
//}
function showGrid() {
    isShowGrid == true ? false : true;
    //绘制网格虚线
    drawGrid(80, 80);
}

//6.显示最新曲线
function showNewCurve() {
    let timeLong = sessionStorage.getItem("timeScale");
    //获取上下限的值
    let topXlimit = timeLong;
    //设置开始时间为最近的三小时
    let bottomXlimit = timeLong - 180;
    //将横坐标的上下限存入cookie中
    $.cookie("bottomXlimit", bottomXlimit);
    $.cookie("topXlimit", topXlimit);
    //根据x轴的上下限重新绘制曲线
    setXAxisRange(bottomXlimit, topXlimit);
}

//7.数据对比
function dataCompare() {
    //取消监听事件
    document.removeEventListener('mousemove', mouseMove);
    //清空已经绘制的十字
    context.clearRect(0, 0, canves_js.width, canves_js.height);
    // 初始化zrender
    var div_zrender = document.getElementById('zrender');
    var zr = zrender.init(div_zrender);
    let yAxisMax = y0;
    let xPosition = 300;
    //第一条线
    let line_one = new zrender.Line({
        shape : {
            x1 : xPosition,
            y1 : 0,
            x2 : xPosition,
            y2 : yAxisMax
        },
        style : {
            stroke : '#fff',
            lineDash : [ 7, 7 ]
        },
        //设置虚线可拖动
        draggable : true
    }).on('mousemove', function(event) {
        line_one.shape.x1 = event.offsetX;
        line_one.shape.x2 = event.offsetX;
        compareText(event.offsetX, event.offsetY, zr, "one");
    });
    zr.add(line_one);
    //绘制文本标注
    compareText(xPosition, yAxisMax / 2, zr, "one");

    xPosition = 600;
    //第二条线
    let line_two = new zrender.Line({
        shape : {
            x1 : xPosition,
            y1 : 0,
            x2 : xPosition,
            y2 : yAxisMax
        },
        style : {
            stroke : '#fff',
            lineDash : [ 7, 7 ]
        },
        //设置虚线可拖动
        draggable : true
    }).on('mousemove', function(event) {
        line_two.shape.x1 = event.offsetX;
        line_two.shape.x2 = event.offsetX;
        compareText(event.offsetX, event.offsetY, zr, "two");
    });
    zr.add(line_two);
    //绘制文本标注
    compareText(xPosition, yAxisMax / 2, zr, "two");
}
//7.数据对比的文本标注
var text_compare_one = new Array();
var text_compare_two = new Array();
function compareText(x, y, zr, lineNo) {
    //清空Text显示
    var sensorArray = parent.getAllSelectSeneor();
    for (j = 0, len = sensorArray.length; j < len; j++) {
        if (lineNo == "one") {
            if (text_compare_one[j] != null && text_compare_one[j] != "") {
                zr.remove(text_compare_one[j]);
            }
        } else {
            if (text_compare_two[j] != null && text_compare_two[j] != "") {
                zr.remove(text_compare_two[j]);
            }
        }

    }
    //从sessionStorage中获取传感器数组中所有的值,并进行遍历显示
    for (j = 0, len = sensorArray.length; j < len; j++) {
        //根据x轴的坐标值和传感器编号获取y的值(带单位)
        //var YAxisValues = getYAxisValueFromSessionStorage(sensorArray[j], x);
        var YAxisValues = parent.getSensorValues(x, sensorArray[j]);
        var AxisColors = parent.getColorFromSessionStorage("sensorColor color" + sensorArray[j]);
        if (lineNo == "one") {
            text_compare_one[j] = new zrender.Text({
                style : {
                    fontSize : '15',
                    text : sensorArray[j] + ':' + YAxisValues,
                    textFill : AxisColors,
                },
            });
            text_compare_one[j].attr('position', [ x, 150 + j * 25 ]);
            zr.add(text_compare_one[j]);

        } else {
            text_compare_two[j] = new zrender.Text({
                style : {
                    fontSize : '15',
                    text : sensorArray[j] + ':' + YAxisValues,
                    textFill : AxisColors,
                },
            });
            text_compare_two[j].attr('position', [ x, 150 + j * 25 ]);
            zr.add(text_compare_two[j]);

        }

    }
}